# -*- coding: utf-8 -*-
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.image import SKUImageSerializer, SKUSerializer
from meiduo_admin.utils import PageNum


class ImageViewSet(ModelViewSet):
    serializer_class = SKUImageSerializer
    pagination_class = PageNum
    queryset = SKUImage.objects.all()

    def list_sku(self, request):
        data = SKU.objects.all()
        seri = SKUSerializer(data, many=True)
        return Response(seri.data, status.HTTP_200_OK)

    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        logo = request.data.get('image')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(logo.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id'].replace('\\', '/')
        sku = request.data.get('sku')

        # 保存品牌
        sku_img = SKUImage.objects.create(sku_id=sku, image=image_url)

        return Response({
            'sku': sku_img.sku_id,
            'image': image_url
        }, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            sku_img = SKUImage.objects.get(id=pk)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        image = request.data.get('image')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id'].replace('\\', '/')
        sku_id = request.data.get('sku')

        # 删除之前的图片
        client.delete_file(sku_img.image.name)

        # 保存品牌
        sku_img.sku_id = sku_id
        sku_img.image = image_url
        sku_img.save()

        return Response({
            'sku': sku_img.sku_id,
            'image': image_url
        }, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            sku_img = SKUImage.objects.get(id=pk)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
        client = Fdfs_client(settings.FASTDFS_PATH)
        client.delete_file(sku_img.image.name)
        sku_img.delete()

        return Response(status=status.HTTP_204_NO_CONTENT)
